import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import { addTab, timeLimit } from '@/utils/utils';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Col,
  Card,
  Input,
  DatePicker,
  Select,
  Button,
  Table,
  Tooltip,
  message,
  Modal,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

const { Item } = Form;
const { info } = Modal;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { pathname } = window.location;

interface BookedRecordsProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  location: { query: any };
  loading: boolean;
  bookedList: any;
  gardenList: any;
  partnersList: any;
  screen: string;
  bizType: Object;
  payType: Object;
  deviceType: Object;
  expressList: any;
}

interface BookedRecordsState {
  searchValues: any;
  pageNum: number;
  numPerPage: number;
  rowId: number;
}

function mapStateToProps(state: any) {
  const {
    bookedRecords: { bookedList, gardenList, partnersList },
    common: {
      INITINFO: {
        bizType,
        payType,
        deviceType,
        expressList,
      },
    },
    global: { screen },
    loading,
  } = state;
  return {
    bookedList,
    gardenList,
    partnersList,
    bizType,
    payType,
    deviceType,
    expressList,
    screen,
    loading: loading.effects['bookedRecords/fetch'],
  };
}

@connect(mapStateToProps)

class BookedRecordsElem extends Component<BookedRecordsProps, BookedRecordsState> {
  columns = [
    {
      title: '上级合作商',
      dataIndex: 'parent_name',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <div
            className="wordOmit"
            style={{ maxWidth: 120 }}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '合作商',
      dataIndex: 'fcs_name',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <div
            className="wordOmit"
            style={{ maxWidth: 120 }}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '小区名称',
      dataIndex: 'garden_name',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <div
            className="wordOmit"
            style={{ maxWidth: 120 }}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '设备类型',
      dataIndex: 'storage_type_desc',
      width: 100,
      render: (text: any) => (text || '--'),
    },
    {
      title: '设备编号',
      dataIndex: 'storage_code',
      width: 100,
      render: (text: string) => (
        <Tooltip title={text}>
          <div
            className="wordOmit"
            style={{ maxWidth: 120 }}
          >
            {text || '--'}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '　运单号',
      dataIndex: 'exp_code',
      width: 120,
      render: (text: string) => (
        <Tooltip title={text}>
          <div
            className="wordOmit"
            style={{ maxWidth: 120 }}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '箱格类型',
      dataIndex: 'cell_type_desc',
      width: 100,
    },
    {
      title: '支付金额',
      dataIndex: 'fcs_income',
      width: 100,
      render: (text: number) => (text / 100).toFixed(2),
    },
    {
      title: '用户类型',
      width: 100,
      dataIndex: 'pay_side_desc',
    },
    {
      title: '支付人手机号',
      dataIndex: 'phone',
      width: 120,
    },
    {
      title: '类型',
      width: 100,
      dataIndex: 'biz_type_desc',
      render: (text: string) => (
        <Tooltip title={text}>
          <div
            className="wordOmit"
            style={{ maxWidth: 120 }}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '结算时间',
      dataIndex: 'create_time',
      width: 200,
    },
  ]

  state: BookedRecordsState = {
    searchValues: {},
    pageNum: 1,
    numPerPage: 20,
    rowId: 0,
  }

  static getDerivedStateFromProps(nextProps: BookedRecordsProps, perState: BookedRecordsState) {
    const { location: { query } } = nextProps;
    const { page, psize, ...searchValues } = query;

    return {
      ...perState,
      searchValues,
      pageNum: Number(page) || 1,
      numPerPage: Number(psize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchAction('partners', { name: '' });
    this.fetchAction('garden');

    this.fetchBizTypeList();
    this.fetchPayTypeList();
    this.fetchDeviceTypeList();

    const { bookedList } = this.props;
    if (bookedList?.list?.length) return;

    this.fetchExpressList();
    this.fetchRechargeList();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageNum, numPerPage } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageNum !== prevState.pageNum
      || numPerPage !== prevState.numPerPage) {
      this.setFieldsValue();
      this.fetchRechargeList();
    }
  }

  // 获取快递公司列表
  fetchExpressList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchExpressList2',
    });
  };

  // 设置表单值
  setFieldsValue = () => {
    const { searchValues }: any = this.state;

    const {
      biz_start_date,
      biz_end_date,
      ...others
    } = searchValues;

    const momentDate = [
      biz_start_date ? moment(biz_start_date) : moment(moment().subtract(4, 'days').format('YYYY-MM-DD')),
      biz_end_date && moment(biz_end_date),
    ];
    others.momentDate = momentDate;

    others.franchise = Number(searchValues['franchise.id']) || undefined;
    others.garden = Number(searchValues['garden.id']) || undefined;
    others.express = Number(searchValues['express.id']) || undefined;


    delete others['franchise.id'];
    delete others['franchise.name'];
    delete others['garden.id'];
    delete others['garden.name'];
    delete others['express.id'];
    delete others['express.name'];

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(others);
  }

  // 获取业务类型列表
  fetchBizTypeList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchBizType',
      payload: {},
    });
  }

  // 获取用户类型
  fetchPayTypeList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchPayType',
      payload: {},
    });
  }

  // 获取设备类型
  fetchDeviceTypeList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'common/fetchDeviceType',
      payload: {},
    });
  }

  // 获取数据
  fetchRechargeList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'bookedRecords/fetch',
      payload: this.getQueryParams(),
    });
  }

  // 获取查询参数
  getQueryParams = () => {
    const { searchValues, pageNum, numPerPage } = this.state;
    const { biz_start_date, biz_end_date } = searchValues;
    const params = {
      ...searchValues,
      pageNum,
      numPerPage,
    };
    params.biz_start_date = biz_start_date || moment(moment().subtract(4, 'days')).format('YYYY-MM-DD');
    params.biz_end_date = biz_end_date || moment(new Date()).format('YYYY-MM-DD');

    return params;
  };

  handleRouter = (routePath: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '统计曲线',
      url: `${routePath}`,
    });
  }

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const {
      partnersList,
      gardenList,
      expressList,
      form: { validateFields },
    } = this.props;

    validateFields((errors, values) => {
      if (!errors) {
        if (!values.storage_type && values.storage_code) {
          message.error('请先选择设备类型后再进行查询!');
          return;
        }

        const {
          franchise,
          garden,
          express,
          momentDate = [],
          ...query
        } = values;

        const franchiseItem = partnersList.filter((item: any) => item.id === franchise);
        const gardenItem = gardenList.filter((item: any) => item.id === garden);
        const expressItem = expressList.filter((item: any) => item.id === express);

        const params = {
          ...query,
          'franchise.id': franchise || '',
          'franchise.name': franchiseItem[0]?.name || '',
          'garden.id': garden || '',
          'garden.name': gardenItem[0]?.name || '',
          'express.id': express || '',
          'express.name': expressItem[0]?.name || '',
          page: 1,
          psize: 20,
        };


        if (momentDate) {
          params.biz_start_date = momentDate[0] ? moment(momentDate[0]).format('YYYY-MM-DD') : '';
          params.biz_end_date = momentDate[1] ? moment(momentDate[1]).format('YYYY-MM-DD') : '';
        }

        const { dispatch } = this.props;
        addTab(dispatch, {
          name: '入账明细',
          url: `${pathname}?${qs.stringify(params)}`,
          isTopMenu: true,
        });
      }
    });
  }

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '入账明细',
      url: pathname,
      isTopMenu: true,
    });
  }

  handlePerPage = (page: number, psize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, page, psize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '入账明显',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  }

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: `bookedRecords/${typeName}`,
      payload,
    });
  }

  // 导出明细
  handleExport = () => {
    info({
      title: '报表正在导出，请稍后至新统计系统-报表管理中下载查看',
    });
    const params = {
      is_export: 1,
      ...this.getQueryParams(),
    };

    this.fetchAction('export', params);
  }

  render() {
    const { pageNum, numPerPage } = this.state;
    const {
      form: { getFieldDecorator },
      loading,
      bookedList,
      partnersList = [],
      gardenList,
      bizType,
      payType,
      deviceType,
      expressList,
    } = this.props;

    const pagination: object = bookedList
      ? {
        total: bookedList.count,
        pageSize: numPerPage,
        current: pageNum,
        onChange: this.handlePerPage,
        showTotal: () => `共${bookedList.count || 0}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        onShowSizeChange: this.handlePerPage,
        showQuickJumper: true,
      }
      : {};

    const dataSource = bookedList.list || [];

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form
            hideRequiredMark
            onSubmit={this.handleSearch}
            className="tableListForm"
          >
            <Row gutter={12}>
              <Col md={12} sm={24}>
                <Form.Item label="起止日期" colon={false}>
                  {getFieldDecorator('momentDate')(
                    <RangePicker
                      style={{ width: '100%' }}
                      format="YYYY/MM/DD"
                      disabledDate={timeLimit}
                      ranges={{
                        今天: [moment().startOf('day'), moment().endOf('day')],
                        本周: [moment().startOf('week'), moment().endOf('week')],
                        本月: [moment().startOf('month'), moment().endOf('month')],
                      }}
                    />,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　合作商" colon={false}>
                  {getFieldDecorator('franchise')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {partnersList.map((item: any) => (
                        item.status === 1
                        && <Option value={item.id} key={item.id}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="用户类型" colon={false}>
                  {getFieldDecorator('pay_side')(
                    <Select placeholder="请选择" allowClear>
                      {Object.keys(payType).map((key: any) => (
                        <Option
                          key={key}
                          value={key}
                        >
                          {payType[key]}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="　　小区" colon={false}>
                  {getFieldDecorator('garden')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {gardenList.map((item: any) => (
                        <Option
                          key={item.id}
                          value={item.id}
                        >
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="设备类型" colon={false}>
                  {getFieldDecorator('storage_type')(
                    <Select placeholder="请选择" allowClear>
                      {Object.keys(deviceType).map((key: any) => (
                        <Option
                          key={key}
                          value={key}
                        >
                          {deviceType[key]}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="设备编号" colon={false}>
                  {getFieldDecorator('storage_code')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="箱格类型" colon={false}>
                  {getFieldDecorator('cell_type')(
                    <Select placeholder="请选择" allowClear>
                      <Option value="0">全部</Option>
                      <Option value="10901">大箱</Option>
                      <Option value="10902">中箱</Option>
                      <Option value="10903">小箱</Option>
                      <Option value="10904">超小箱</Option>
                      <Option value="10905">大(宽)箱</Option>
                      <Option value="10906">中(宽)箱</Option>
                      <Option value="10907">小(宽)箱</Option>
                      <Option value="10908">超小(宽)箱</Option>
                      <Option value="10909">文件箱</Option>
                      <Option value="10910">文件(宽)箱</Option>
                      <Option value="10911">超大箱</Option>
                      <Option value="10912">超大(宽)箱</Option>
                    </Select>,
                  )}
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="业务类型" colon={false}>
                  {getFieldDecorator('biz_type')(
                    <Select placeholder="请选择" allowClear>
                      {Object.keys(bizType).map((key: any) => (
                        <Option
                          key={key}
                          value={key}
                        >
                          {bizType[key]}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="快递公司" colon={false}>
                  {getFieldDecorator('express')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => option.props.children
                        .toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {expressList.map((express: any) => (
                        <Option
                          key={express.id}
                          value={express.id}
                          style={{
                            backgroundImage: `url(${express.img})`,
                            backgroundSize: '18px,18px',
                            backgroundRepeat: 'no-repeat',
                            backgroundPosition: '8px center',
                            padding: '0 33px ',
                            lineHeight: '32px',
                          }}
                        >
                          {express.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　运单号" colon={false}>
                  {getFieldDecorator('exp_code')(<Input
                    allowClear
                    placeholder="请输入"
                  />)}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              className="smallButton marginR16"
              type="primary"
              size="small"
              onClick={() => this.handleRouter('/partner/withdrawalMoney/list/detail')}
            >
              统计曲线
            </Button>
            <Tooltip title={bookedList.count > 6000 ? ' 导出明细最多导出6000条' : ''}>
              <Button
                disabled={bookedList.count > 6000}
                className="smallButton"
                type="primary"
                size="small"
                onClick={this.handleExport}
              >
                导出明细
              </Button>
            </Tooltip>
            <span style={{ float: 'right' }}>支付总金额：{bookedList.total_fcs_income / 100}元</span>
          </div>

          <Table
            rowKey="id"
            loading={loading}
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            scroll={{ x: 1400 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
      </Fragment>
    );
  }
}

export default Form.create()(BookedRecordsElem);
